import 'package:winkai/db/dao/ses_dao.dart';
import 'package:winkai/db/database.dart';
import 'package:winkai/helper/user_helper.dart';

import '../ses_service.dart';

class SesServiceImp implements SesService {
  @override
  Future<List<SesInfo>> selectAll() {
    //查询所有会话时，去筛查删除信息
    return rootDb.sesDao.selectAll(UserHelper().userId, true);
  }

  @override
  String? getUserIdBySessionId(String sessionId) {
    var tag = '->';
    if (sessionId.contains(tag)) {
      var start = sessionId.indexOf(tag) + tag.length;
      var userInfo = sessionId.substring(start, sessionId.length);
      return userInfo.split(':').firstOrNull;
    }
    return null;
  }

  @override
  String? getUserNameBySessionId(String sessionId) {
    var tag = '->';
    if (sessionId.contains(tag)) {
      var start = sessionId.indexOf(tag) + tag.length;
      var userInfo = sessionId.substring(start, sessionId.length);
      return userInfo.split(':').lastOrNull;
    }
    return null;
  }

  @override
  Future<SesInfo?> selectSingleOrNull(String id) {
    return rootDb.sesDao.selectSingleOrNull(id);
  }

  @override
  Future<void> resetUnReadNum(String id) async {
    await rootDb.sesDao.resetUnReadNum(id);
    await rootDb.msgDao.resetIsRead(id);
  }

  @override
  Future<void> resetAllUnReadNum(String accountId) async {
    var sessions = await rootDb.sesDao.selectAll(accountId);
    _syncAccountUnReadNum(sessions);
  }

  @override
  Future<void> deleteById(String id) async {
    await rootDb.sesDao.deleteById(id);
  }

  @override
  Future<void> createSession(
    String sessionId, {
    int? lastMsgId,
    bool isUpdate = false,
  }) async {
    var userId = getUserIdBySessionId(sessionId);
    await rootDb.sesDao.insertOrUpdate(
      accountId: UserHelper().userId,
      lastMsgId: lastMsgId,
      id: sessionId,
      userId: userId,
    );
  }

  /// 同步数量到用户级
  void _syncAccountUnReadNum(List<SesInfo> sessions) {
    var unReadMsgNum = 0;
    for (var item in sessions) {
      unReadMsgNum += item.session.unReadNum;
    }
    UserHelper().update(unReadMsgNum);
  }
}
